<template>
    <div style="margin: 20px;">
            <el-form size="small" :inline="true" @submit.native.prevent>
                <el-form-item label="Input" prop="roleName">
                    <el-input
                        v-model="searchValue"
                        placeholder="Input"
                        clearable
                        style="width: 240px"
                        @keyup.enter.native="handleQuery()"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery()">
                        Search
                    </el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="handleReset">Reset</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button
                        type="warning"
                        plain
                        icon="el-icon-refresh"
                        size="mini"
                        @click="handleSyncFileDir"
                        v-hasPermi="['business:first:config']"
                    >SyncFileDir
                    </el-button>
                </el-form-item>
            </el-form>
            <el-table
                v-loading="tabLoading"
                :data="treeData"
                style="width: 100%;margin-bottom: 20px;"
                row-key="id"
                default-expand-all
                :height="tableMaxHeight"
                :tree-props="{children: 'children'}">
                <el-table-column
                    prop="label"
                    label="文件"
                    sortable
                    width="auto">
                </el-table-column>
                <el-table-column
                    prop="remarkName"
                    label="文件名称"
                    sortable
                    width="auto">
                </el-table-column>
                <el-table-column
                    prop="Operate"
                    label="操作">
                    <template slot-scope="scope">
                        <el-row :gutter="20">
                            <!--                                <el-col :span="2">
                                                                <el-button
                                                                    v-if="scope.row.isFile"
                                                                    type="text"
                                                                    size="mini"
                                                                    @click="() => downloadFile(scope.row)">
                                                                    下载
                                                                </el-button>
                                                            </el-col>-->
                            <el-col :span="6" v-hasPermi="['business:first:visible']">
                                <el-button
                                    v-if="scope.row.visible === 'y'"
                                    type="danger"
                                    icon="el-icon-error"
                                    size="mini"
                                    plain
                                    @click="() => hideFile(scope.row,'n')"
                                > 隐藏
                                </el-button>
                                <el-button
                                    v-if="scope.row.visible === 'n'"
                                    type="info"
                                    icon="el-icon-success"
                                    size="mini"
                                    plain
                                    @click="() => hideFile(scope.row,'y')"
                                > 取消隐藏
                                </el-button>
                            </el-col>
                            <el-col  :span="5">
                                <el-button
                                    v-if="scope.row.isFile && scope.row.label.endsWith('.pdf')"
                                    type="success"
                                    icon="el-icon-view"
                                    size="mini"
                                    plain
                                    @click="() => viewPdf(scope.row)"
                                > 预览
                                </el-button>
                            </el-col>
                            <el-col :span="6">
                                <el-button
                                    v-if="scope.row.isFile && scope.row.label.endsWith('.pdf')"
                                    type="primary"
                                    icon="el-icon-s-flag"
                                    size="mini"
                                    plain
                                    v-hasPermi="['business:first:assign']"
                                    @click="() => onOpen(scope.row)"
                                > Assign
                                </el-button>
                            </el-col>
                            <el-col :span="6">
                                <el-button
                                    v-if="scope.row.isFile && scope.row.label.endsWith('.pdf')"
                                    type="warning"
                                    icon="el-icon-document"
                                    size="mini"
                                    plain
                                    v-hasPermi="['business:first:assign']"
                                    @click="() => onOpenHistory(scope.row)"
                                > Assign History
                                </el-button>
                            </el-col>
                            <!--                                <el-col :span="4">-->
                            <!--                                    <el-switch-->
                            <!--                                        v-if="scope.row.isFile && scope.row.label.endsWith('.pdf')"-->
                            <!--                                        v-model="scope.row.readStatus"-->
                            <!--                                        @change="viewChange(scope.row.readStatus,scope.row.filePath)"-->
                            <!--                                        active-text="是"-->
                            <!--                                        inactive-text="否">-->
                            <!--                                    </el-switch>-->
                            <!--                                </el-col>-->
                        </el-row>
                    </template>
                </el-table-column>
            </el-table>

        <!-- 指派 -->
        <el-dialog title="Assign" :visible.sync="assignOpen" width="50%" :append-to-body="true"
                   :close-on-click-modal="false">
                <el-row :gutter="15">
                    <el-form ref="assignElForm" :model="assignForm" :rules="assignRule" size="medium" label-width="100px">
                        <el-col :span="24">
                            <el-row :gutter="15">
                                <el-col :span="24">
                                    <el-form-item label="FileName" prop="fileName">
                                        <el-input v-model="assignForm.fileName" disabled clearable
                                                  :style="{width: '100%'}"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-col>
                        <el-col :span="12">
                            <el-row :gutter="15">
                                <el-col :span="24">
                                    <el-form-item label="FileType" prop="fileType">
                                        <el-select v-model="assignForm.fileType" placeholder="ChooseType" clearable :disabled="assignSelectEnable"
                                                   :style="{width: '100%'}">
                                            <el-option v-for="(item, index) in  dict.type.dcc_file_type" :key="index" :label="item.label"
                                                       :value="item.value" :disabled="item.disabled"></el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-col>
                        <el-col :span="12">
                            <el-row :gutter="15">
                                <el-col :span="24">
                                    <el-form-item label="Emergency" prop="emergencyLevel">
                                        <el-select v-model="assignForm.emergencyLevel" placeholder="Choose Emergency Level" clearable :disabled="assignSelectEnable"
                                                   :style="{width: '100%'}">
                                            <el-option v-for="(item, index) in dict.type.dcc_emergency_level" :key="index" :label="item.label"
                                                       :value="item.value" :disabled="item.disabled"></el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-col>
                        <el-col :span="24">
                            <el-row :gutter="15">
                                <el-col :span="12">
                                    <el-form-item label="Date" prop="fileDate">
                                        <el-date-picker v-model="assignForm.fileDate" disabled format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"
                                                        :style="{width: '100%'}" placeholder="Choose Date" clearable></el-date-picker>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="Due Date" prop="dueDate">
                                        <el-date-picker type="datetime" v-model="assignForm.dueDate" format="yyyy-MM-dd HH:mm:ss"  default-time="12:00:00"
                                                        value-format="yyyy-MM-dd HH:mm:ss" :style="{width: '100%'}" clearable></el-date-picker>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-col>
                        <el-col :span="24">
                            <el-row :gutter="15">
                                <el-col :span="24">
                                    <el-form-item label="Target" prop="assignTreeData">
                                        <el-scrollbar class="scrollbarClass">
                                            <el-tree
                                                v-loading="loading"
                                                ref="assignTreeRef"
                                                :data="assignTreeData"
                                                show-checkbox
                                                node-key="id"
                                                @check-change="handleNodeClick"
                                                :default-expand-all="true"
                                                :props="defaultProps">
                                            </el-tree>
                                        </el-scrollbar>

                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-col>
                    </el-form>
                </el-row>
                <div slot="footer">
                    <el-button @click="onClose">取消</el-button>
                    <el-button type="primary" @click="handleAssignConfirm">确定</el-button>
                </div>
        </el-dialog>
        <!--指派历史-->
        <el-dialog title="Assign Status" :visible.sync="assignHistoryOpen" width="90%" :append-to-body="true"
                   :close-on-click-modal="false">
            <file-assign-record :file-assign-id="assignFileId" v-if="assignHistoryOpen"/>
            <div slot="footer">
                <el-button @click="onClose">取消</el-button>
                <el-button type="primary" @click="onClose">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<style scoped>
</style>
<script>
import {
    addFilesConfig, assignEmail,
    deleteFilesConfig, editVisible, getAssignSource,
    getFilesConfig, getFirstDirId,
    listAllByDirectory,
    listDirectory,
    syncFiles
} from "@/api/business/first";
import {download, downloadBlob} from "@/utils/request";
import FileAssign from "@/views/business/first/fileAssign.vue";
import UserViewRecord from "@/views/business/first/userViewRecord.vue";
import FileAssignRecord from "@/views/business/first/fileAssignRecord.vue";
import dict from "@/store/modules/dict";
import {findByFileId} from "@/api/business/assign";
import {parseTime} from "@/utils/ruoyi";
export default {
    dicts: ['dcc_emergency_level','dcc_file_type'],
    data() {
        return {
            defaultProps: {
                children: 'children',
                label: 'name'
            },
            showConfig: false,
            newFileForm: {
                menuName: '',
                perms: ''
            },
            open: false,
            filesConfigList: [],
            activeName: '',
            originTreeData: [],
            checkedTreeData:[],
            treeData: [],
            panelData: [],
            subTreeData: [],
            pdfList: [], // 存储PDF文件信息的数组
            pdfUrl: '',
            searchValue: '',
            viewFileData: [],
            selectFileDir:'',
            assignOpen:false,
            assignHistoryOpen:false,
            assignForm:{
                fileId:'',
                fileName:'',
                filePath:'',
                remarkName:'',
                fileDate:'',
                fileType:'',
                emergencyLevel:'',
                dueDate:'',
                sendData:[]
            },
            assignTreeData: [],
            assignRule: {
                fileType: [{
                    required: true,
                    message: 'Choose Type',
                    trigger: 'change'
                }],
                emergencyLevel: [{
                    required: true,
                    message: 'Choose Emergency Level',
                    trigger: 'change'
                }],
                dueDate: [{
                    required: true,
                    message: 'Choose Due Date',
                    trigger: 'change'
                }],
                field124: [{
                    required: true,
                    message: '请输入单行文本',
                    trigger: 'blur'
                }],
            },
            assignFileId:"",
            loading: false,
            tabLoading:false,
            assignSelectEnable:false
        };
    },
    components: {FileAssignRecord, FileAssign,UserViewRecord},
    computed: {
        tableMaxHeight() {
            return window.innerHeight - 215 + 'px';
        }
    },
    methods: {
        handleNodeClick(data) {
            this.checkedTreeData = this.$refs.assignTreeRef.getCheckedNodes()
        },
        filterMethod(query, item) {

        },
        onOpenHistory(item) {
            this.assignFileId = item.id
            this.assignHistoryOpen = true;
        },
        onOpen(item) {
            this.loading = true
            // 打开指派弹窗
            this.checkedTreeData = []
            this.assignOpen = true;
            const date = new Date();
            findByFileId(item.id).then(res => {
                const data = res.data
                if (data){
                    this.assignForm.emergencyLevel =  data.level
                    this.assignForm.fileType = data.fileType
                    this.assignSelectEnable = true
                }else{
                    this.assignForm.emergencyLevel = 'one'
                    this.assignForm.fileType = 'new'
                    this.assignSelectEnable = false
                }
                this.assignForm.fileDate =parseTime(date)
                this.assignForm.dueDate = parseTime(new Date( date.getTime() + 1000* 60 * 60 * 24 * 7));
                this.assignForm.fileName = item.label;
                this.assignForm.fileId = item.id;
                this.assignForm.filePath = item.filePath
                this.assignForm.remarkName = item.remarkName
                getAssignSource(item.id).then(res => {
                    this.assignTreeData = res.data;
                    this.loading = false
                })
            })
        },
        onClose() {
            this.assignOpen = false;
            this.assignHistoryOpen = false;
        },
        handleAssignConfirm() {
            this.$refs['assignElForm'].validate(valid => {
                if (valid) {
                    this.assignForm.sendData = this.checkedTreeData
                    this.$modal.confirm("Are you sure to assign?").then(()=>{
                        assignEmail(this.assignForm).then(res=>{
                            if (res.code === 200){
                                this.$message.success("Assign Success")
                            }
                        })
                        this.$refs['assignElForm'].resetFields()
                        this.onClose()
                    })
                }
            })
        },
        // 同步文件
        handleSyncFileDir() {
            syncFiles().then(res => {
                this.$message.success("Sync Success");
                this.listFileConfig();
                this.parsePanel();
            })
        },
        // 搜索当前tab的文件
        handleFilter(item, searchValue) {
            let newChildren = []
            // 递归遍历本文件夹下的子文件夹
            let children = item.children
            if (children.length > 0) {
                for (let i = 0; i < children.length; i++) {
                    const oldChildren = children[i]
                    // 如果有符合的加入
                    let newChildrenItem = this.handleFilter(oldChildren, searchValue)
                    if (newChildrenItem !== null) {
                        newChildren.push(newChildrenItem)
                    }
                }
            }
            // 处理当前文件夹下的文件
            let label = item.label
            // 如果搜索的值中包含字母转化成大写
            let searchValueCopy = '';
            for (let i = 0; i < searchValue.length; i++) {
                if (/^[a-zA-Z]*$/.test(searchValue.charAt(i))) {
                    searchValueCopy += searchValue.charAt(i).toUpperCase()
                } else {
                    searchValueCopy += searchValue.charAt(i)
                }
            }
            // 找到最后的文件名
            let fileNameCopy = label
            let newFileName = ''
            fileNameCopy = fileNameCopy.replace(".pdf", "");
            // 如果文件名的值中包含字母转化成大写
            for (let i = 0; i < fileNameCopy.length; i++) {
                if (/^[a-zA-Z]*$/.test(fileNameCopy.charAt(i))) {
                    newFileName += fileNameCopy.charAt(i).toUpperCase()
                } else {
                    newFileName += fileNameCopy.charAt(i)
                }
            }
            item.children = newChildren
            // 如果当前字段不包含搜索  但是 子文件包含 或者当前字段包含搜索，且没有子文件，则返回当前节点
            if (newFileName.indexOf(searchValueCopy.toUpperCase()) < 0 && newChildren.length > 0 ||
                newFileName.indexOf(searchValueCopy.toUpperCase()) > -1 && newChildren.length === 0) {
                return item
            } else {
                return null
            }
        },
        // 触发搜索回车
        handleQuery() {
            let data = JSON.parse(JSON.stringify(this.originTreeData))
            let newData = []
            data.forEach(item => {
                const newItem = this.handleFilter(item, this.searchValue)
                if (newItem !== null) {
                    newData.push(newItem)
                }
            })
            if (newData.length < 1) {
                this.$message.warning("No file contain")
                this.treeData = JSON.parse(JSON.stringify(this.originTreeData))
            } else {
                this.treeData = JSON.parse(JSON.stringify(newData))
            }
        },
        handleReset() {
            this.searchValue = ''
            this.treeData = JSON.parse(JSON.stringify(this.originTreeData))
        },
        handleClick(tab, event) {
            // 点击tab切换，非配置面板
            if ("config" !== this.activeName ) {
                this.tabLoading = true
                this.treeData = []
                // 重新请求数据
                this.loadTreeData(this.activeName)
            }
            // 重置搜索框
            this.searchValue = ''
        },
        downloadFile(node) {
            const data = {
                employeeId: this.$store.getters.employeeId,
                name: this.$store.getters.name,
                deptId: this.$store.getters.deptId,
                fileName: node.filePath,
                readStatus: "o"
            }
        },
        // 点击预览按钮，查看pdf
        hideFile(node,visible) {
            editVisible(node.id,visible).then(res => {
                this.$modal.msgSuccess("操作成功");
                this.parsePanel();
            })
        },
        // 点击预览按钮，查看pdf
        viewPdf(node) {
            const data = {
                employeeId: this.$store.getters.employeeId,
                name: this.$store.getters.name,
                deptId: this.$store.state.user.deptId,
                fileName: node.filePath,
                readStatus: "o"
            }
            downloadBlob("/common/downloadAny", {'fileName': node.filePath+"\\"+node.label}, node.label).then(res => {
                const binaryData = [];
                binaryData.push(res);
                //获取blob链接
                this.pdfUrl = window.URL.createObjectURL(new Blob(binaryData, {type: 'application/pdf'}));
                window.open(this.pdfUrl);
                window.URL.revokeObjectURL(this.pdfUrl);
            })
            this.parsePanel();
        },
        // 构建面板数据
        loadTreeData(dirId) {
            listAllByDirectory(dirId).then((res) => {
                const resData = res.data
                // 处理当前文件夹下的所有数据
                this.treeData  = this.parseData(resData);
                // 准备初始数据，方便重置
                this.originTreeData = JSON.parse(JSON.stringify(this.treeData))
                this.tabLoading = false
            }).catch((error) => {
                this.treeData= []
            })
        },
        parsePanel() {
            // 获取一级文件夹的文件DIR
            getFirstDirId().then(res=>{
                if (res.data){
                    this.panelData = [{
                        label: "一级文件",
                        id: res.data.id
                    }]
                    this.activeName = this.panelData[0].id
                    this.loadTreeData(res.data.id)
                }
            })
        },

        // 处理文件夹下的数据
        parseData(data) {
            let res = [];
            // 递归处理当前文件夹下的文件夹
            const dirs = data.dir;
            if (dirs && dirs.length > 0) {
                for (const dir of dirs) {
                    let fileName = dir.dirName;
                    let arr = this.parseData(dir)
                    res.push({
                        isFile: false,
                        id: dir.dirId,
                        label: fileName,
                        remarkName: fileName,
                        filePath: dir.path,
                        children: arr,
                        visible: 'y',
                    })
                }
            }
            // 处理当前文件夹下的文件
            const files = data.files
            if (files && files.length > 0) {
                for (const file of files) {
                    // 全部显示 todo
                    // if (!file.fileName.endsWith("pdf")) {
                    //     continue
                    // }
                    let fileName = file.fileOriginName;
                    if (file.visible === 'n' && !this.$auth.hasPermi("business:dcc:visible")) {
                        continue
                    }
                    res.push({
                        isFile: true,
                        id: file.id,
                        label: fileName,
                        remarkName: file.remarkName,
                        filePath: file.filePath,
                        children: [],
                        visible: file.visible,
                    })
                }
            }
            return res;
        },
        // 获取权限配置
        listFileConfig() {
            getFilesConfig().then(res => {
                this.filesConfigList = res.data;
            })
        },
        handleAddDir() {
            this.newFileForm = {};
            this.open = true;
        },
        handleAddFile() {
            this.newFileForm = {};
        },
        handleDelete(row) {
            const id = row.menuId;
            this.$modal.confirm('Delete FileDir？').then(function () {
                return deleteFilesConfig(id);
            }).then(() => {
                this.listFileConfig();
                this.$modal.msgSuccess("Delete Success");
            }).catch(() => {
            });
        },
        /** 提交按钮 */
        submitForm() {
            if (undefined === this.newFileForm.menuName || null === this.newFileForm.menuName || this.newFileForm.menuName === '') {
                this.$message({
                    message: '请输入文件夹名称',
                    type: 'error'
                });
                return;
            }
            addFilesConfig(this.newFileForm.menuName).then(res => {
                this.open = false;
                this.$modal.msgSuccess("Add Success");
                this.listFileConfig();
            })
        },
        cancel() {
            this.open = false;
            this.fileAddOpen = false;
        },
    },
    created() {
        // 如果有权限则请求文件夹权限列表
        if (this.$auth.hasPermi("business:first:config")) {
            this.listFileConfig();
            this.showConfig = true;
        }
        this.parsePanel();
    }
};

</script>
<style>
.scrollbarClass {
    height: 300px;
}
.el-scrollbar__wrap {
    overflow-x: hidden;
}
</style>
